package com.lry.basic.algorithm.stack;

import java.util.Stack;

/**
 * @author:刘仁有
 * @desc: 逆波兰表达式求值
 * @email:953506233@qq.com
 * @data:2019/12/4
 */
public class EvalRPN {
    public static void main(String[] args) {
        System.out.println(EvalRPN.evalRPN(new String[]{"2", "1", "+", "3", "*"}));
    }

//    输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
//    输出: 22
//    解释:
//            ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
//            = ((10 * (6 / (12 * -11))) + 17) + 5
//            = ((10 * (6 / -132)) + 17) + 5
//            = ((10 * 0) + 17) + 5
//            = (0 + 17) + 5
//            = 17 + 5
//            = 22
    public static int evalRPN(String[] tokens) {
        if(null==tokens||tokens.length==0)
            return 0;
        Stack<String>stack = new Stack<>();
        for (String token:tokens) {
            int i1 = 0,i2 = 0;
            if("+".equals(token)||
               "-".equals(token)||
               "*".equals(token)||
               "/".equals(token)){
                if(stack.isEmpty())return 0;
                String s1 =  stack.pop();
                i1 = Integer.parseInt(s1);
                if(stack.isEmpty())return 0;
                String s2 =  stack.pop();
                i2 = Integer.parseInt(s2);
            }
            if("+".equals(token)){
               int result = i2+i1;
               stack.push(""+result);
            }else if("-".equals(token)){
                int result = i2-i1;
                stack.push(""+result);
            }else if("*".equals(token)){
                int result = i2*i1;
                stack.push(""+result);
            }else if("/".equals(token)){
                if(i1==0) return 0;
                int result = i2/i1;
                stack.push(""+result);
            }else{ //运算数 ，只能包含 + ，- ，0~9
                if(!checkNumber(token))
                    return 0;
                stack.push(token);
            }
        }
        return Integer.parseInt(stack.pop());
    }

    /**
     * 只能包含 + ，- ，0~9
     * @param token 运算数
     * @return
     */
    private static boolean checkNumber(String token){
        if(null==token||token.length()==0)
            return false;
        char[] charArr = token.toCharArray();
        for(int i=0;i<charArr.length;i++){
            char c = charArr[i];
            if(i==0&&(c=='+'||c=='-')) continue;
            //从第二个字符开始，如果不是数字就false
            if(c-48<0||c-48>9){
                return false;
            }
        }
        return true;
    }

}
